<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <el-input
          v-model="query.taskName"
          clearable
          size="small"
          placeholder="请输入任务名称"
          style="width: 200px;"
          class="filter-item"
        />
        <el-select
          v-model="query.status"
          filterable
          clearable
          size="small"
          placeholder="请选择转换状态"
          class="filter-item"
          style="width: 200px"
        >
          <el-option v-for="item in statusOptions" :key="item.key" :label="item.label" :value="item.key" />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!-- 功能按钮 -->
      <crudOperation :permission="permission" />
    </div>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      style="width: 100%;"
      :data="crud.data"
      @filter-change="crud.handleFilterChange"
      @select="crud.selectChange"
      @select-all="crud.selectAllChange"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column v-if="columns.visible('taskName')" :show-overflow-tooltip="true" label="任务名称" prop="taskName" min-width="150" />
      <el-table-column v-if="columns.visible('analyzeType')" label="分析类型" prop="analyzeType" min-width="150" />
      <el-table-column v-if="columns.visible('status')" label="分析状态" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === 'TODO'" type="info">待分析</el-tag>
          <el-tag v-if="scope.row.status === 'PROCESSING'">分析中</el-tag>
          <el-tag v-if="scope.row.status === 'FINISH'" type="success">完成</el-tag>
          <el-tag v-if="scope.row.status === 'FAIL'" type="danger">失败</el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('startTime')" prop="startTime" label="开始时间" min-width="150">
        <template slot-scope="scope">
          <div>
            <i class="el-icon-time" />
            <span style="margin-left: 5px">{{ scope.row.startTime }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('endTime')" prop="endTime" label="结束时间" min-width="150">
        <template slot-scope="scope">
          <div>
            <i class="el-icon-time" />
            <span style="margin-left: 5px">{{ scope.row.endTime }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('upUserName')" prop="upUserName" label="更新人" />
      <el-table-column v-if="columns.visible('upTs')" prop="upTs" label="更新时间" min-width="150" />
      <el-table-column v-if="columns.visible('total')" prop="total" label="分析详情">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleClick(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('total')" prop="total" label="表迁移情况">
        <template slot-scope="scope">
          <el-button v-if="isExistTask(scope.row.transferTask, 'TABLE_TRANSFER')" type="text" size="small">已创建</el-button>
          <span v-else>无任务</span>
        </template>
      </el-table-column>
      <!-- <el-table-column v-if="columns.visible('total')" prop="total" label="数据迁移详情">
        <template slot-scope="scope">
          <el-button v-if="isExistTask(scope.row.transferTask, 'DATA_TRANSFER')" type="text" size="small">查看任务</el-button>
          <span v-else>无任务</span>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('total')" prop="total" label="脚本迁移详情">
        <template slot-scope="scope">
          <el-button v-if="isExistTask(scope.row.transferTask, 'SCRIPT_TRANSFER')" type="text" size="small">查看任务</el-button>
          <span v-else>无任务</span>
        </template>
      </el-table-column> -->
    </el-table>
    <!--分页组件-->
    <pagination />
    <!--脚本导入-->
    <el-dialog
      v-if="crud.status.cu === 1"
      :visible.sync="crud.status.cu === 1"
      append-to-body
      :close-on-click-modal="false"
      title="脚本导入"
      top="5vh"
      width="1200px"
      @close="crud.cancelCU()"
    >
      <el-form ref="form" :model="form" :rules="rules" :inline="true" label-width="130px">
        <el-row>
          <el-col :span="22">
            <el-steps :active="active" finish-status="success" simple>
              <el-step title="分析清单" />
              <el-step title="确认血缘" />
            </el-steps>
          </el-col>
          <el-col :span="2">
            <div class="grid-content bg-purple-light">
              <el-button icon="el-icon-question" class="assist" @click="helpFormVisible = true">帮助</el-button>
            </div>
          </el-col>
        </el-row>
        <div v-if="active === 0">
          <create-task v-if="active === 0" ref="createTask" v-model="form" />
          <div slot="footer" class="dialog-footer" style="width:100%;text-align: center;margin-top: 10px">
            <el-button @click="crud.cancelCU()">关 闭</el-button>
            <el-button type="primary" @click="toAnalyze">下一步(分析)</el-button>
          </div>
        </div>
        <div v-if="active === 1">
          <analyze-result v-if="active === 1" v-model="form" />
          <div class="dialog-footer" style="width:100%;text-align: center;margin-top: 10px">
            <el-button type="primary" @click="back">上一步</el-button>
            <el-button type="primary" @click="createTransferTask">创建任务</el-button>
          </div>
        </div>
      </el-form>
    </el-dialog>
    <!-- 查看帮助文档 -->
    <el-dialog title="帮助" :visible.sync="helpFormVisible" width="1200px">
      <div>
        <script-analyze-helper />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/expand/script/transfer/CRUD.operation'
import pagination from '@crud/Pagination'
import createTask from './components/createTask/create-task'
import analyzeResult from './components/analyzeResult/index'
import scriptAnalyzeHelper from './components/helper/helper'
import scriptAnalyzeTaskApi from '@/api/script/analyze/script-analyze-task'

// crud交由presenter持有
const defaultCrud = CRUD({ title: '脚本转换任务', url: '/api/script/analyze/task', crudMethod: { ...scriptAnalyzeTaskApi }})
const defaultForm = {
  pkId: null,
  scriptImportType: 'FILE',
  analyzeType: '',
  taskName: null,
  isHiddenUploadFile: false,
  isHiddenValu: false,
  isHiddenImportType: false,
  proceduresList: [],
  transferTaskList: [],
  transferTask: [],
  fileList: [],
  tmpFileList: [],
  sourceConnPkId: null,
  targetConnPkId: null,
  dbName: null,
  status: 'TODO'
}
export default {
  name: 'ScriptAnalyzeTask',
  components: {
    crudOperation,
    rrOperation,
    pagination,
    analyzeResult,
    createTask,
    scriptAnalyzeHelper
  },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    var validateTaskName = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback(new Error('请输入任务名称'))
      } else {
        scriptAnalyzeTaskApi.findListByPage(value).then(rsp => {
          let isExistFlag = false
          if (rsp.total > 0) {
            rsp.content.forEach(item => {
              if (value === item.taskName) {
                isExistFlag = true
              }
            })
          }
          if (isExistFlag) {
            callback(new Error('任务名称已存在！'))
          } else {
            callback()
          }
        })
      }
    }
    return {
      active: 0,
      projectList: [],
      helpFormVisible: false,
      taskName: null,
      permission: {
        add: ['admin', 'scriptAnalyze:add'],
        del: ['admin', 'scriptAnalyze:del']
      },
      statusOptions: [
        { key: 'TODO', label: '待转换' },
        { key: 'PROCESSING', label: '转换中' },
        { key: 'FINISH', label: '完成' },
        { key: 'FAIL', label: '失败' }
      ],
      rules: {
        taskName: [
          { required: true, validator: validateTaskName, trigger: 'blur' }
        ],
        scriptImportType: [
          { required: true, message: '请选择脚本导入方式', trigger: 'change' }
        ],
        analyzeType: [
          { required: true, message: '请选择迁移类型', trigger: 'change' }
        ],
        sourceConnPkId: [
          { required: true, message: '请选择源服务器', trigger: 'change' }
        ],
        targetConnPkId: [
          { required: true, message: '请选择目标服务器', trigger: 'change' }
        ],
        dbName: [
          { required: true, message: '请选择数据库名', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
  },
  created() {
    this.crud.resetQuery(false)
  },
  methods: {
    [CRUD.HOOK.beforeToAdd](crud) {
      this.active = 0
      crud.resetForm()
    },
    [CRUD.HOOK.afterAddCancel](crud) {
      crud.refresh()
    },
    async toAnalyze() {
      if (this.crud.form.status === 'TODO') {
        this.$refs['form'].validate((valid) => {
          if (valid && this.checkHasScriptList()) {
            const dataForm = JSON.parse(JSON.stringify(this.crud.form))
            this.formatFileList(dataForm)
            scriptAnalyzeTaskApi.add(dataForm).then(data => {
              this.crud.form.pkId = data
              this.crud.form.isHiddenValu = true
              this.crud.form.isHiddenUploadFile = true
              this.crud.form.status = 'PROCESSING'
              this.active++
            })
          }
        })
      } else {
        this.active++
      }
    },
    formatFileList(dataForm) {
      const fileList = []
      dataForm.fileList.forEach(item => {
        fileList.push(item.filePath)
      })
      dataForm.fileList = fileList
    },
    checkHasScriptList() {
      if (this.crud.form.fileList.length < 1 && this.crud.form.proceduresList.length < 1) {
        this.$notify({ title: '告警', message: '请选择上传或选择要转换的脚本！', type: 'warning' })
        return false
      }
      return true
    },
    back() {
      this.active--
      this.form.isHiddenValu = true
      this.form.isHiddenUploadFile = true
    },
    next() {
      this.active++
    },
    // 查看转换清单详情
    handleClick(data) {
      this.form.pkId = data.pkId
      this.form.isHiddenValu = false
      this.form.isHiddenUploadFile = false
      this.form.isHiddenImportType = true
      this.form.taskName = data.taskName
      this.form.transferTask = data.transferTask
      this.form.sourceConnPkId = data.sourceConnPkId
      this.form.targetConnPkId = data.targetConnPkId
      this.form.status = data.status
      this.form.transferTaskList = data.transferTask.map(obj => obj.transferTaskType)
      this.active = 1
      if (data.status === 'TODO') {
        this.active = 0
      }
      this.crud.status.add = 1
    },
    isExistTask(transferTask, type) {
      return transferTask.find(item => item.transferTaskType === type) !== undefined
    },
    createTransferTask() {
      const dataForm = JSON.parse(JSON.stringify(this.crud.form))
      this.formatFileList(dataForm)
      scriptAnalyzeTaskApi.createTransferTask(dataForm).then(data => {
        this.$notify({ title: '成功', message: '创建任务成功！', type: 'success' })
        this.crud.cancelCU()
        this.crud.refresh()
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.assist {
  min-height: 46px;
  color: #fff;
  background-color: #ff4949;
  border-color: #ff4949;
}
</style>
